import requests  # 网络请求
import hashlib  # MD5加密
import time  # 用于获取时间戳
import json  # Json操作


class Translate(object):
    APP_ID = "你的APPID"
    KEY = "你的KEY"

    def __init__(self, APPID, KEY):
        self.APP_ID = APPID
        self.KEY = KEY

    # 获取MD5加密的字符串
    def _get_md5_str(self, source_key):
        md5 = hashlib.md5()
        md5.update(source_key.encode("utf-8"))
        return md5.hexdigest()

    # 获取请求的地址
    def _get_request_url(self, source_str, source_language, dst_language):
        current_time = str(time.time())
        source_key = self.APP_ID + source_str + current_time + self.KEY
        md5_key = self._get_md5_str(source_key)
        url = "http://api.fanyi.baidu.com/api/trans/vip/translate?" \
              "q=" + source_str + "&from=" + source_language + "&to=" + dst_language + "&appid=" + self.APP_ID \
              + "&salt=" + current_time + "&sign=" + md5_key
        return url

    # 格式化返回的数据
    def _format_data(self, response_str):
        # 将返回的json数据转换为字典
        json_data = json.loads(response_str)
        # print(json_data)
        # 取出翻译后的目标语言
        return json_data['trans_result'][0]['dst']

    # 翻译
    def translate(self, source_str, source_language, dst_language):
        # 构建请求的Url
        url = self._get_request_url(source_str, source_language, dst_language)
        # 进行请求
        response = requests.get(url=url)
        print(response.text)
        # 对返回的数据进行格式化
        try:
            translate_str = self._format_data(response.text)
        except:
            return None
        return translate_str
